package com.example.musicapp.view;


import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.musicapp.R;
import com.example.musicapp.adapter.MusicSearchAdapter;
import com.example.musicapp.application.MyApp;
import com.example.musicapp.base.BaseActivity;
import com.example.musicapp.bean.Music;
import com.example.musicapp.contract.ISearchContract;
import com.example.musicapp.presenter.SearchPresenter;
import com.example.musicapp.storage.factory.DaoFactory;
import com.example.musicapp.view.widget.FlowLayout;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends BaseActivity<SearchPresenter> implements ISearchContract.ISearchUi, View.OnClickListener {

    private EditText mEtSearch;
    private List<String> mHistoryList;
    private List<String> mHotList = new ArrayList<>();
    private LinearLayout mLvSearchBefore;
    private LinearLayout mLvSearchAfter;
    private FlowLayout mFlHistory;
    private FlowLayout mFlHot;
    private final List<Music> mMusicList = new ArrayList<>();

    private SmartRefreshLayout smartRefreshLayout;
    private RecyclerView mRecyclerView;
    private MusicSearchAdapter myAdapter;
    private int curPage =1;
    private String mSearchWord;
    private boolean judgeLoadMore;
    private boolean mJudgeSetInVisible = true;
    ProgressDialog mProgressDialog ;
    @Override
    public SearchPresenter onBindPresenter() {
        return new SearchPresenter(this);
    }

    @Override
    protected void initData() {
        showHistoryWord();
        getHotWord();
    }

    @Override
    protected void initView() {
        Button mBtnSearch = findViewById(R.id.btn_search);
        mEtSearch = findViewById(R.id.et_search);
        TextView mTvClearHistory = findViewById(R.id.tv_clear_history);
        TextView mTvClearHot;
        mFlHistory = findViewById(R.id.flow_history);
        mFlHot = findViewById(R.id.flow);
        mTvClearHot = findViewById(R.id.tv_clear_hot_word);
        mLvSearchAfter = findViewById(R.id.lv_search_result);
        mLvSearchBefore = findViewById(R.id.lv_search_before);

        smartRefreshLayout = findViewById(R.id.refresh_layout_search);


        mRecyclerView = findViewById(R.id.rv_search);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        //smartRefreshLayout.autoLoadMore();//自动加载
        //smartRefreshLayout.autoRefresh();//自动刷新
        smartRefreshLayout.setEnableAutoLoadMore(true);//是否启用列表惯性滑动到底部时自动加载更多
        smartRefreshLayout.setEnableLoadMore(true);//是否启用加载更多功能
        smartRefreshLayout.setEnableRefresh(true);//是否启用下拉刷新功能

        myAdapter = new MusicSearchAdapter(mMusicList);
        myAdapter.setOnItemClickListener((view, position) -> {
            Intent turnToPlayIntent = new Intent(SearchActivity.this,PlayActivity.class);
            turnToPlayIntent.putExtra("musicList", (Serializable) mMusicList);
            turnToPlayIntent.putExtra("position",position);
            startActivity(turnToPlayIntent);
        });
        mTvClearHot.setOnClickListener(this);
        mBtnSearch.setOnClickListener(this);
        mTvClearHistory.setOnClickListener(this);
    }

    @Override
    public void initListener() {
        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {

            curPage = 1;
            requestSearch(mSearchWord,curPage);
            refreshLayout.closeHeaderOrFooter();


        });
        smartRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            if (judgeLoadMore) {
                requestSearch(mSearchWord,++curPage);
                refreshLayout.finishLoadMore();
            }
        });
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_search;
    }

    @Override
    public void searchSuccess(List<Music> list) {
        mProgressDialog.cancel();
        mMusicList.addAll(list);

        runOnUiThread(() -> {

            if (mJudgeSetInVisible) {
                mLvSearchBefore.setVisibility(View.INVISIBLE);
                mLvSearchAfter.setVisibility(View.VISIBLE);
                mJudgeSetInVisible = false;
            }

            showMusicList(mMusicList);
        });

    }

    private void showMusicList(List<Music> list){
        myAdapter.setMusicList(list);

        myAdapter.notifyDataSetChanged();

        mRecyclerView.setAdapter(myAdapter);
    }


    @Override
    public void searchFailure() {

    }

    @Override
    public void getHotSuccess(List<String> list) {
        mHotList.addAll(list);


        changHistoryUi(mFlHot,mHotList);
    }

    @Override
    public void addHistoryWord(String historyWord) {
        if (DaoFactory.getHistoryDao(this).findOneRecord(historyWord)){
            DaoFactory.getHistoryDao(this).deleteOneRecord(historyWord);
        }
        getPresenter().addHistory(historyWord);
        mHistoryList = DaoFactory.getHistoryDao(MyApp.getContext()).findAllRecord();

    }


    @Override
    public void clearHistoryWord() {
        DaoFactory.getHistoryDao(this).deleteAllRecord();
        mHistoryList = DaoFactory.getHistoryDao(this).findAllRecord();
        changHistoryUi(mFlHistory,mHistoryList);
    }

    @Override
    public void showHistoryWord() {
        mHistoryList = DaoFactory.getHistoryDao(this).findAllRecord();
        changHistoryUi(mFlHistory,mHistoryList);
    }

    @Override
    public void clearHot() {
        mHotList = new ArrayList<>();
        changHistoryUi(mFlHot,mHotList);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_search:
                mSearchWord = mEtSearch.getText().toString();
                addHistoryWord(mSearchWord);
                showHistoryWord();
                requestSearch(mSearchWord,curPage);
                showDialog();
                break;

            case R.id.tv_clear_history:
                clearHistoryWord();
                changHistoryUi(mFlHistory,mHistoryList);
                break;
            default:break;
        }
    }

    /**
     * 改变历史信息的ui
     * @param flowLayout flow布局
     * @param list 集合
     */
    private void changHistoryUi(FlowLayout flowLayout,List<String> list) {
        //往容器内添加TextView数据
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(10, 5, 10, 5);
        if (flowLayout != null) {
            flowLayout.setBackgroundColor(Color.BLACK);
            flowLayout.removeAllViews();
        }
        for (int i = list.size()-1; i>=0; i--) {
            TextView tv = new TextView(this);
            tv.setPadding(28, 10, 28, 10);
            tv.setText(list.get(i));
            tv.setMaxEms(10);
            tv.setSingleLine();
            tv.setTextColor(Color.BLACK);
            tv.setBackgroundResource(R.drawable.shape_big_login_btn);


            tv.setLayoutParams(layoutParams);

            int finalI = i;
            tv.setOnClickListener(v -> {
                addHistoryWord(list.get(finalI));
                showHistoryWord();
                mSearchWord =list.get(finalI);
                requestSearch(list.get(finalI), curPage);
                showDialog();
                Toast.makeText(getApplicationContext(),list.get(finalI), Toast.LENGTH_SHORT).show();
            });
            assert flowLayout != null;
            flowLayout.addView(tv, layoutParams);
        }
    }

    private void getHotWord(){
        getPresenter().getHotWord();
    }


    private void requestSearch(String word, int curPage){
        judgeLoadMore =true;

        getPresenter().search(word,curPage);
    }

    /**
     * 加载对话框，加载数据
     */
    private void showDialog(){
        mProgressDialog =new ProgressDialog(this);
        mProgressDialog.setTitle("数据加载中");
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.show();
    }


}